package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component//将拦截器放入容器
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override   //preHandle:在进入controller之前进行拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.验证用户是否登录了
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");

        if(employee == null){
            //2.非法访问,返回错误
            System.out.println("用户未登录,非法访问!");

            //3.返回错误信息
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");//组装对象
            String json = new ObjectMapper().writeValueAsString(resultInfo);//转为json
            response.getWriter().write(json);//返回json

            return false;//禁止通行
        }else {//3.登录成功
            EmployeeHolder.set(employee);
            return true;
        }
    }

    @Override   //postHandle:在离开controller之后进行拦截
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override   //离开服务器
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();// 清空threadLocal里面的内容
    }
}
